package xyz.labmem.main.modular.common.controller

import cn.hutool.core.date.DateUtil
import cn.hutool.core.io.FileUtil
import cn.hutool.core.util.ClassUtil
import cn.hutool.core.util.ZipUtil
import com.alibaba.excel.EasyExcel
import io.swagger.annotations.Api
import io.swagger.annotations.ApiModel
import io.swagger.annotations.ApiOperation
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import xyz.labmem.base.core.annotion.NoNeedLogin
import xyz.labmem.base.core.error.AppException
import xyz.labmem.base.sys.base.BaseController
import xyz.labmem.base.sys.consts.PathPrefixConst
import xyz.labmem.main.modular.common.service.FileDownLoadService
import javax.servlet.http.HttpServletResponse

/**
 * @Author lty
 * @Date 2022/1/10 11:03
 */
@RestController
@Api(tags = ["临时接口"])
@RequestMapping("${PathPrefixConst.COMMON_PATH_PREFIX}tempPub")
class ComTempPubController : BaseController() {

    @NoNeedLogin
    @GetMapping("getTemplateZip")
    @ApiOperation(value = "获取所有模板")
    fun getTemplateZip(response: HttpServletResponse) {
        val temp = System.getProperty("java.io.tmpdir")
        val path = "$temp/所有模板-${DateUtil.current()}"
        val map = mapOf(
            "zhgk" to "综合概况数据展示",
            "gmjj" to "国民经济",
            "rmfk" to "人民防空",
            "xxly" to "新型领域",
            "rmwz" to "人民武装",
            "zzdy" to "政治动员",
            "jtys" to "交通运输",
            "wqzb" to "武器装备",
        )
        try {
            map.keys.forEach { key ->
                val thisPath = "${path}/${map[key]}"
                FileUtil.mkdir(thisPath)
                ClassUtil.scanPackage("xyz.labmem.main.modular.app.${key}.entity").forEach {
                    val name = it.getAnnotation(ApiModel::class.java).value.replace("表", "")
                    EasyExcel.write("${thisPath}/${name}.xlsx", it)
                        .sheet("模板")
                        .doWrite(arrayListOf(it.getDeclaredConstructor().newInstance()))
                }
            }
            FileDownLoadService.download(response, ZipUtil.zip(path))
            log.info("下载完成！")
        } catch (ex: Exception) {
            throw AppException(ex)
        } finally {
            //释放资源
            FileUtil.del(path)
            if (FileUtil.exist("${path}.zip")) {
                FileUtil.del("${path}.zip")
            }
        }
    }

}